<template>
  <div class="w-full h-full">
    <ul class="w-full h-full min-w-32 flex flex-col " ref="ulList">
      <Scrollbar>
        <template v-for="(item, index) in props.list" :key="index">
          <li v-if="item['ai'] == receiveAi" :class="[
            `litouch${item['id']}`,
            'flex',
            'flex-row',
            'relative',
            'px-2',
            'py-4',
            'h-20',
            'items-center',
            'justify-between',
            'cursor-pointer',
            'rounded',
            'gap-3',
            'select-none',
            {
              'bg-orange-200': item['id'] == data.userId,
            },
          ]" @touchstart="handleDown(index, item)" @touchmove="handleMove" @touchend="handleUp(index, item)">
            <!-- 要长按 各个id 需要接收到数组的id item['id'] touchmove事件：当用户按住屏幕滑动时  -->
            <div class="h-12 w-12">
              <!-- <img v-if="item['to_avatar']" class="rounded h-full" :src="item['to_avatar']" :alt="item['to_id']" /> -->
              <div class="rounded h-full w-full bg-orange-400 text-white text-[20px] flex items-center justify-center">
                {{ item['to_name'][0] }}
              </div>
            </div>
            <div class="flex-1 flex flex-row items-center justify-between  overflow-hidden">
              <div class="flex-1 flex flex-col gap-1 min-w-0 relative">
                <div v-if="item['new'] == 1" class="w-3 h-3 rounded-full bg-red-600 absolute right-0 top-0" />
                <span class="truncate text-[14px] flex flex-row gap-2">
                  {{ identification(index, item) }} {{ item['to_name'] }} · {{ item['from_name'] }}
                  <Robot class="text-orange-500" v-if="item['ai'] == 1" />
                </span>
                <span class="truncate text-[13px] text-gray-500" v-html="textToEmoji(item['content'])" />
              </div>
              <div class="w-20 text-right">
                <!-- whitespace-nowrap 使文本不自动换行  -->
                <span class="text-gray-600 text-[12px] whitespace-nowrap mr-3">
                  {{
                    item['msg_time']
                      ? item['msg_time'].slice(5, 16)
                      : ''
                  }}
                </span>
              </div>
            </div>
            <!-- 过渡组件 -->
            <transition name="slide-fade" mode="out-in">
              <!-- 第三步 在父组件中@事件名，编写回调函数 接收的值为t，传递到爷组件的事件名为selectMenu，值为回调函数t和data.userId -->
              <Menu :show="data.userId == item['id'] && showMenu" :user-id="`${data.userId}`" @select-menu="(t) => {
                showMenu = false;
                $emit('selectMenu', t, data.userId);
              }" @cancel="showMenu = false; data.userId = ''" />
              <!-- 点击遮罩层 Menu隐藏 data.userId 为空值 -->
            </transition>
          </li>
        </template>
      </Scrollbar>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { type IProps } from './props';
import { type IEmits } from './emits';
import { textToEmoji } from '@/utils/render';
import './style.css'
import Scrollbar from '../scrollbar/Scrollbar.vue';
import Menu from '../menu/Menu.vue';
import Robot from '../icon/Robot.vue';

const ulList = ref<HTMLElement>()

const props = withDefaults(defineProps<IProps>(), {
  list: () => [],
  receiveAi: String
});

const emits = defineEmits<IEmits>();

const data: { userId: string; timer: number } = reactive({
  userId: '',
  timer: 0,
});

const showMenu = ref(false);

// 长按开始
// 记录时间的增长
const t = ref(0);
// 是否在滑动
const isScroll = ref(false);
// 按下
const handleDown = async (index: number, item: Record<string, any>) => {
  // 每次按下 重置t的值为零
  t.value = 0;
  // 创建一个时间间隔执行 每隔0秒执行一次 
  data.timer = setInterval(() => {
    if (t.value >= 300) {
      // 确定你长按的是哪一个
      data.userId = item['id'];
      // 展示Menu组件显示
      showMenu.value = true;
      // 清除data.timer的值
      clearInterval(data.timer)
    }
    // 通常在计时器中 这个值一般放在末尾
    t.value += 1;
    // isLongPress.value = true
  }, 0);
}

// 手拖住屏幕滑动的时候 isScroll为真
const handleMove = () => {
  // 抬起的时候 
  isScroll.value = true;
}

// 长按抬起
const handleUp = (index: number, item: Record<string, any>) => {
  // 当长按结束之后 就结束掉data.timer
  clearInterval(data.timer)
  if (t.value >= 300) {
    t.value = 0;
    emits('longTouch', index, item);
    // 当touchmove为false 并且 
  } else if (!isScroll.value && !showMenu.value) {
    t.value = 0;
    data.userId = item['id'];
    emits('click', index, item);
  }
  if (isScroll.value) {
    isScroll.value = false;
  }
}

// 标识
const identification = (index: number, item: Record<string, any>) => {
  let idtitle = ''
  if (item['stranger'] == 1) {
    idtitle = '[M]'
  } else if (item['stranger'] == 2) {
    idtitle = '[Z]'
  }
  return idtitle
}

const event = {
  reset() {
    data.userId = '';
  },
};

// 子向父传
defineExpose({
  reset: event.reset,
  ulList,
});
</script>